<template id="template">
  <div id="myChart">
  </div>
</template>

<script>
//导入echarts库
import echarts from 'echarts';

//声明myChart变量,方便动态加载数据
let myChart = null;
let option = null;

export default {
  name: "MyChart",
  props: ["weightData"],
  //挂载后再载入echarts组件,防止dom未生成导致错误
  mounted() {
    //初始化echarts组件
    this.drawChart();
  },
  methods: {
    //初始化echarts组件
    drawChart: function () {
      myChart = echarts.init(document.getElementById('myChart'),
          'light');
      //选项
      option = {
        title: {
          text: '每日体重',
          left: 'center'
        },
        dataset: {
          source: []
        },
        grid: {
          left: 100,
          right: 100
        },
        xAxis: {
          type: 'category',
          name: '日期',
          //格式化横座标日期显示样式 不用time之后就不需要设置了
          // axisLabel: {
          //   "formatter": (value) => {
          //      console.log('label' + value);
          //   }
          // },
          min: 'dataMin',
          max: 'dataMax',
          boundaryGap: false,
          splitNumber: 10,
        },
        yAxis: {
          name: '体重',
          max: (value) => {
            return Math.ceil(value.max / 5) * 5 + 5;
          },
          min: value => {
            return Math.floor(value.min / 5) * 5 - 5;
          },
          minInterval: 5,
          maxInterval: 5,
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line'
          }
        },
        series: [{
          name: '每日体重',
          type: 'line',
          encode: {x: 0, y: 1},
          label: {}
        }],
        dataZoom: {
          id: 'DateZoom',
          type: 'slider',
          minValueSpan: 7,

        }
      };
      myChart.setOption(option, true);
    },
    //加载数据
    loadData: function () {
      option.dataset.source = this.weightData;
      myChart.setOption(option, true);
    }
  },
  watch: {
    //数据更新后,刷新图表
    weightData: function () {
      this.loadData();
    }
  }
}
</script>

<style scoped>
#myChart {
  height: 500px;
  width: 700px;
}
</style>